import React, {
  useEffect,
  useImperativeHandle,
  useRef,
  forwardRef,
  useState,
} from "react";
import * as echarts from "echarts";
import echartsTheme from "../echartsTheme";
import { Empty } from "antd";

interface EChartComponentProps {
  option?: echarts.EChartsOption;
  style?: React.CSSProperties;
  onChartInit?: (chartInstance: echarts.ECharts) => void;
}

export interface EChartRef {
  setLoading: (status: boolean) => void;
  setOptions: (newOptions: echarts.EChartsOption) => void;
  clear: () => void;
}

const EChartComponent = forwardRef<EChartRef, EChartComponentProps>(
  ({ option, style, onChartInit }, ref) => {
    const chartRef = useRef<HTMLDivElement>(null);
    const chartInstanceRef = useRef<echarts.ECharts | null>(null);
    const [isEmpty, setIsEmpty] = useState(true);
    useEffect(() => {
      echarts.registerTheme("customTheme", echartsTheme);
      if (chartRef.current) {
        const instance = echarts.init(chartRef.current, "customTheme");
        chartInstanceRef.current = instance;
        if (option) instance.setOption(option);

        if (onChartInit) {
          onChartInit(instance);
        }

        return () => {
          instance.dispose();
          chartInstanceRef.current = null;
        };
      }
    }, [option, onChartInit]);

    const setOptions = (newOptions: echarts.EChartsOption) => {
      newOptions.series.length > 0 ? setIsEmpty(false) : setIsEmpty(true);
      if (chartInstanceRef.current) {
        chartInstanceRef.current.setOption(newOptions);
        chartInstanceRef.current.hideLoading();
      }
    };

    const setLoading = (status: boolean) => {
      if (chartInstanceRef.current) {
        status
          ? chartInstanceRef.current.showLoading()
          : chartInstanceRef.current.hideLoading();
      }
    };
    const clear = () => {
      if (chartInstanceRef.current) {
        chartInstanceRef.current.clear();
      }
    };
    useImperativeHandle(ref, () => ({
      setOptions,
      clear,
      setLoading, // 补充暴露 showLoading 方法
    }));

    return (
      <div style={{ position: "relative" }}>
        <div
          className="echart-container"
          ref={chartRef}
          style={{ width: "100%", height: "400px", ...style }}
        />
        {isEmpty && (
          <Empty style={{ position: "absolute", top: "30%", left: "35%" }} />
        )}
      </div>
    );
  }
);

export default EChartComponent;
